import datetime

from ctaBase import *
from ctaTemplate import *
from indicators import Indicators
from utils import MinKLineGenerator

class MyStrategy(CtaTemplate):
    """第一个策略编写，实现基本的买卖操作"""
    def __init__(self) -> None:
        super().__init__()
        # 参数映射表
        self.paramMap = {
            'exchange': '交易所',
            'vtSymbol': '合约',
        }

        # 状态映射表
        self.varMap = {
            'trading': '交易中',
            'pos': '持仓'
        }

        self.widgetClass = KLWidget
        self.widget: KLWidget = None
        self.indicators: Indicators = None 
        self.mul:Dict[str,MinKLineGenerator] = {}
        self.kline_generator = MinKLineGenerator = None
        # 定义k线周期-默认值
        self.R = 6
        self.kline_style_x = 'M1'
        self.trading = False

        self.rsi_val_c = 0
        self.rsi_val_p = 0

    def onTick(self, tick: TickData):
        """收到行情TICK推送"""
        super().onTick(tick)

        # 过滤涨跌停和集合竟价
        if tick.lastPrice or tick.askPrice1 or tick.bidPrice1:
            self.kline_generator.tick_to_kline(tick)
            
    def onStart(self) -> None:
        super().onStart()
        self.output('交易所：',self.exchange,'合约：',self.vtSymbol)

         #获取k线数据
        self.kline_generator = MinKLineGenerator(
            real_time_callback=self.real_time_callback,
            callback=self.callback,
            exchange=self.exchange,
            instrument=self.vtSymbol,
            style=self.kline_style_x
        )

        # self.c_x_arr = self.kline_generator.producer.rsi(self.R,array=True)
        
        # self.output('rsi数据:', c_x_arr[-1])

    def real_time_callback(self, kline: KLineData) -> None:
        """使用收到的实时推送 K 线来计算指标并更新线图"""
        # self.output('real_time_callback_kline:',kline.close,kline.datetime)
        rsi_val = self.kline_generator.producer.rsi(self.R,array=True)
        self.rsi_val_c,self.rsi_val_p = rsi_val[-1],rsi_val[-2]

    
    def callback(self, kline: KLineData) -> None:
        """接受 K 线回调"""    
        self.output('callback_kline:',kline.close,kline.datetime)
        c_x_arr = self.indicators.rsi(self.R,array=True)
        self.output('callback_rsi数据:', c_x_arr[-1],c_x_arr[-2])
        self.output('real_time_callback_rsi数据:', self.rsi_val_c,self.rsi_val_p)

    def onStop(self):
        super().onStop()